package com.xzr.hospitalregister.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.adapter.DthzItemAdapter;
import com.xzr.hospitalregister.adapter.DthzYSItemAdapter;
import com.xzr.hospitalregister.base.BaseActivity;
import com.xzr.hospitalregister.config.HttpUrl;
import com.xzr.hospitalregister.entity.DthzListItem;
import com.xzr.hospitalregister.entity.DthzYSListItem;
import com.xzr.hospitalregister.util.DataCleanManager;
import com.xzr.hospitalregister.util.GetTokenFromClientAPK;
import com.xzr.hospitalregister.util.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/1/24 0024.
 */

public class HallWaitingActivity extends BaseActivity {
    private TextView tv_time, tv_mTime, te_pd_gdt, te_docname, tv_huanzhe2, tv_huanzhe3, tv_huanzhe4, tv_content;
    private static final int msgKey1 = 1;
    private static final int msgKey2 = 5;
    private RecyclerView mRecyclerview, recyclerView;
    private DthzItemAdapter dthzItemAdapter = null;
    private DthzYSItemAdapter dthzYSItemAdapter = null;
    private List<DthzListItem> data = new ArrayList<>();
    private List<DthzYSListItem> data2 = new ArrayList<>();
    private Button but_ertongbjb;

    private Context context;
    private String deviceId;
    String str = "A,B;C:D:E:F:G";
    public String newName;

    private JSONObject jsonObject;
    ;
    private JSONArray jsonData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getSupportActionBar().hide();// 隐藏ActionBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏
        setContentView(R.layout.activity_hallwaiting);
        initWidget();
        deviceId = GetTokenFromClientAPK.getMacAddress1();
        if (!TextUtils.isEmpty(deviceId)) {
            deviceId = deviceId.replaceAll("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]", ""); //去标点符号
            deviceId = deviceId.toLowerCase();//大写转换成小写
            Toast.makeText(HallWaitingActivity.this, deviceId, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(HallWaitingActivity.this, "MAC地址为空", Toast.LENGTH_LONG).show();
        }
        initData();
    }

    @Override
    public void initWidget() {
        super.initWidget();
        te_docname = (TextView) findViewById(R.id.te_docname);
//        tv_time = (TextView) findViewById(R.id.tv_time);
//        tv_mTime = (TextView) findViewById(R.id.tv_mTime);
        te_pd_gdt = (TextView) findViewById(R.id.te_pd_gdt);
        te_pd_gdt.setSelected(true);//如果textview不滚动就加上这句代码
//        new TimeThread().start();////////////
        new TimeThreadjh().start();
        tv_content = (TextView) findViewById(R.id.tv_custom_content);
        tv_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rename();
            }
        });
        SharedPreferences sp = getSharedPreferences("HosSet", MODE_PRIVATE);
        String username = sp.getString("hosValue", "博爱县妇幼保健院");
        tv_content.setText(username);
        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview_dthz);
        but_ertongbjb = (Button) findViewById(R.id.but_ertongbjb);
    }

    @Override
    public void initData() {
        super.initData();
        //应用程序最大可用内存
        int maxMemory = ((int) Runtime.getRuntime().maxMemory()) / 1024 / 1024;
//应用程序已获得内存
        long totalMemory = ((int) Runtime.getRuntime().totalMemory()) / 1024 / 1024;
//应用程序已获得内存中未使用内存
        long freeMemory = ((int) Runtime.getRuntime().freeMemory()) / 1024 / 1024;
//        System.out.println("---> maxMemory=" + maxMemory + "M,totalMemory=" + totalMemory + "M,freeMemory=" + freeMemory + "M");
        Log.e("TAG", "==============================---> maxMemory=" + maxMemory + "M,totalMemory=" + totalMemory + "M,freeMemory=" + freeMemory + "M");
        /////////////
        DataCleanManager.clearAllCache(this);///
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = sdf.format(new Date());
        String[] nowDateStrSplits = nowDateStr.split("-");
//        tv_time.setText(nowDateStr);
        try {
            JSONObject jsonObject = new JSONObject(getIntent().getStringExtra("jsonData"));
            JSONArray jsonData = jsonObject.getJSONArray("rows");
//            Log.e("TAG", "排队列表 jsonData.getJSONObject(0).getString(\"FLAG\")+++" + jsonData.getJSONObject(0).getString("FLAG"));
//            Log.e("TAG", "诊室 jsonData.getJSONObject(0).getString(\"ROOMNAME\")+++" + jsonData.getJSONObject(0).getString("ROOMNAME"));
            for (int i = 0; i < jsonData.length(); i++) {
                JSONObject jsonObject1 = jsonData.getJSONObject(i);
                data2.add(new DthzYSListItem(jsonObject1.getString("DOCTNAME")));
                but_ertongbjb.setText(jsonObject1.getString("name"));
                JSONArray jsonData2 = jsonObject1.getJSONArray("jhry");
                data.add(new DthzListItem(jsonObject1.getString("DOCTNAME"), jsonData2.toString(), "(" + jsonObject1.getString("ROOMNAME") + ")"));
            }
//                Log.e("TAG","获取到的jsonObject +++"+jsonObject);
//                Log.e("TAG","获取到的jsonData +++"+jsonData);
            showAllMotherSonInfo();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

//        private String mac = "00606e5458dd";//儿童保健部—排队
    private String mac = "00606e5458d4";//妇女保健部—排队
//    private String mac = "dcc0db78aa5b";
//    private String mac = "9cb2b228e24c";
    public void getMotherYFXXTKFromRemote() {
        data2.clear();

        final List<DthzListItem> dataTemp = new ArrayList<>();
//        Toast.makeText(HallWaitingActivity.this,"排队网络请求的MAC"+deviceId,Toast.LENGTH_LONG).show();
//        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"deptcode\":\"" + 8888 + "\"+,\"flag\":\"" + 1 + "\"}",new Handler() {
//        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"mac\":\"" + mac + "\"+,\"flag\":\"" + 1 + "\"}", new Handler() {
        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"mac\":\"" + mac + "\"}", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.arg1 == -1) {
                    Toast.makeText(HallWaitingActivity.this, "服务器水逆了...", Toast.LENGTH_SHORT).show();
//                    System.out.println("*****   " + (String) msg.obj);
                } else if (msg.arg1 == 1) {
                    try {
                        jsonObject = new JSONObject((String) msg.obj);
                        jsonData = jsonObject.getJSONArray("rows");
//                        Log.e("TAG", "排队列表 jsonData.getJSONObject(0).getString(\"FLAG\")+++" + jsonData.getJSONObject(0).getString("FLAG"));
//                        Log.e("TAG", "诊室 jsonData.getJSONObject(0).getString(\"ROOMNAME\")+++" + jsonData.getJSONObject(0).getString("ROOMNAME"));
                        for (int i = 0; i < jsonData.length(); i++) {
                            JSONObject jsonObject1 = jsonData.getJSONObject(i);
                            data2.add(new DthzYSListItem(jsonObject1.getString("DOCTNAME")));
                            but_ertongbjb.setText(jsonObject1.getString("name"));
                            JSONArray jsonData2 = jsonObject1.getJSONArray("jhry");
                            dataTemp.add(new DthzListItem(jsonObject1.getString("DOCTNAME"), jsonData2.toString(), "(" + jsonObject1.getString("ROOMNAME") + ")"));
                        }
//                            Log.e("TAG","获取到的jsonObject +++"+jsonObject);
//                            Log.e("TAG","获取到的jsonData +++"+jsonData);
//                            Log.e("TAG","获取到的(String) msg.obj +++"+(String) msg.obj);
                        aa = true;
                        data.clear();
                        for (int i = 0; i < dataTemp.size(); i++) {
                            data.add(dataTemp.get(i));
                        }
//                            showAllMotherSonInfo();
                        dthzItemAdapter.notifyDataSetChanged();
//                        System.out.println("按下了back键   onKeyDown()     子线程  again   notifyDataSetChanged***********************" + Thread.currentThread().getName());
//                        System.out.println("YCMotherSonInfoselectFragment   " + (String) msg.obj);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
//                System.out.println("排队列表   " + (String) msg.obj);
//                Log.e("TAG", "排队列表 data+++" + data);
//                Log.e("TAG", "排队列表 obj+++" + (String) msg.obj);
            }
        });
    }
//    public class TimeThread extends Thread {
//        @Override
//        public void run() {
//            do {
//                try {
//                    Thread.sleep(1000);
//                    Message msg = new Message();
//                    msg.what = msgKey1;
//                    mHandler.sendMessage(msg);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            } while (true);
//        }
//    }

//    private Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case msgKey1:
////                    long sysTime = System.currentTimeMillis();
////                    CharSequence sysTimeStr = DateFormat.format("EEEE HH:mm:ss", sysTime);//HH :24小时制   hh:12小时制
////                    tv_mTime.setText(sysTimeStr);
//                    break;
//
//                default:
//                    break;
//            }
//        }
//    };

    boolean aa = true;
    Thread recyclerViewOneTimeRemoteDataThread;
    LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    ;

    /**
     * 展示所有从服务器上拉下来的数据
     */
    private void showAllMotherSonInfo() {
        mRecyclerview.setLayoutManager(manager);
        dthzItemAdapter = new DthzItemAdapter(data, this);


        mRecyclerview.setAdapter(dthzItemAdapter);
        dthzItemAdapter.setOnClickListener(new DthzItemAdapter.OnClickListener() {
            @Override
            public void onLongClickListener(int position) {
            }
        });
        Log.e("data ", data.toString());
        mRecyclerview.scrollToPosition(6);
        if (aa) {
            recyclerViewOneTimeRemoteDataThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    loopShow();
                }
            });
            recyclerViewOneTimeRemoteDataThread.start();
            aa = false;
        }
    }


    //    public synchronized void loopShow(){
//        try {
////            Log.e("loopShow","*****************************************    data  size"+data.size()+"    "+(Double)(data.size()/5.0)+"    "+ data.size()*1.0/5);
////            Log.e("loopShow","*****************************************"+recyclerViewOneTimeRemoteDataThread.isAlive());
//            int times= (int) Math.ceil(data.size()/5.0);
//
//            for (int i = 1; i <= times; i++) {
//                Thread.sleep(4000);
//                Message message = handler.obtainMessage();
//                if (i<times)
//                message.arg1 = i*5-5;
//                if (i==times)
//                    message.arg1 = data.size()-5;
////                Log.e("aaa","i:"+i+"        times:"+times+"        message.arg1:"+message.arg1);
//                handler.sendMessage(message);
//                if (i== Math.ceil(data.size()/5.0))
//                    loopShow();
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }
////////////////////////////////////
    public synchronized void loopShow() {
        try {
//            Log.e("loopShow","*****************************************    data  size"+data.size()+"    "+(Double)(data.size()/5.0)+"    "+ data.size()*1.0/5);
            Log.e("loopShow", "*****************************************" + "");

            int times = (int) Math.ceil(data.size() / 5.0);
            List<Integer> fileList = new ArrayList<Integer>();
            fileList.add(times);
            while (!fileList.isEmpty()) {
//                System.out.println("按下了back键   onKeyDown()     子线程   ***********************" + Thread.currentThread().getName());
                for (int i = 1; i <= times; i++) {
//                    System.out.println("按下了back键   onKeyDown()     子线程" + Thread.currentThread().getName());
                    Thread.sleep(4000);
                    Message message = handler.obtainMessage();
                    if (i < times)
                        message.arg1 = i * 5 - 5;
                    if (i == times)
                        message.arg1 = data.size() - 5;
//                Log.e("aaa","i:"+i+"        times:"+times+"        message.arg1:"+message.arg1);
                    handler.sendMessage(message);
                    if (i == Math.ceil(data.size() / 5.0))
                        fileList.add(i);
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    ////////////////////////////////////
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            mRecyclerview.scrollToPosition(msg.arg1);
            manager.scrollToPositionWithOffset(msg.arg1, 0);
//            Log.e("handleMessage",""+msg.arg1);
        }
    };

    public class TimeThreadjh extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(20000);
                    Message msg = new Message();
                    msg.what = msgKey2;
                    mHandlerjh.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private Handler mHandlerjh = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey2:
                    getMotherYFXXTKFromRemote();
                    try {
                        Log.e("TAG", "获取到的应用缓存大小*********************" + DataCleanManager.getTotalCacheSize(HallWaitingActivity.this));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 显示设置IP对话框
     */
    public void rename() {
        Log.v("TAG", "$$$$$$$$$$$$$inrename..");
        // layout = (LinearLayout) getLayoutInflater().inflate(R.layout.myedit,
        // null);
        LayoutInflater factory = LayoutInflater.from(this);
        View textEntryView = factory.inflate(R.layout.dialog_hos_name, null);
        // removeView();
        //内部局部类，只能访问方法的final类型的变量
        final EditText mname_edit = (EditText) textEntryView
                .findViewById(R.id.tv_acitivity_ip_set_hoename);
        // 不是用这个方法获取EditText的内容的
        // mname_edit.addTextChangedListener(mTextWatcher);

        // create a dialog
        new AlertDialog.Builder(HallWaitingActivity.this)
                .setIcon(R.drawable.btn_certain_blue)
                .setTitle(R.string.soft_hosname_update_title)
                .setView(textEntryView)
                .setNegativeButton(R.string.soft_update_ip_later,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub

                            }

                        })
                .setPositiveButton(R.string.soft_update_ip_updatebtn,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // dialog.
                                // TODO Auto-generated method stub
                                Log.v("TAG", "你点击了确定");
                                if (!mname_edit.getText().toString().equals("")) {
                                    newName = mname_edit.getText().toString();
                                    tv_content.setText(newName);
                                    SharedPreferences sp = getSharedPreferences("HosSet", MODE_PRIVATE);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("hosValue", newName);
                                    edit.commit();
                                }
                                // newName = mname_edit.getText().toString();

                                Log.v("TAG", "$$$$$btn.setText(newName);");
                            }

                        }).show();

    }
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//    }

    /**
     * 监听Back键按下事件,方法1:
     * 注意:
     * super.onBackPressed()会自动调用finish()方法,关闭
     * 当前Activity.
     * 若要屏蔽Back键盘,注释该行代码即可
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        System.out.println("按下了back键   onBackPressed()");
    }


    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            System.out.println("按下了back键   onKeyDown()");
//            System.out.println("按下了back键   onKeyDown()" + Thread.currentThread().getName());
//            finish();
            System.exit(0);
//            return false;
            return super.onKeyDown(keyCode, event);
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        System.exit(0);
//        System.out.println("执行 onDestroy()");
//    }
}
